// pages/release-buyshop/release-buyshop.js
import { Shop } from '../../models/shop'
import { check } from '../../util/identityCheck'
import { Publish } from '../../models/other'
const publishModel = new Publish()
const shopModel = new Shop()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import { RedPacket } from '../../models/redpacket'

let packetModel = new RedPacket()
function getShareId() {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') {
    // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    id: null,
    showPopup: {
      buyWay: false,
      buyLocation: false,
      buyArea: false
    },
    buyLocationList: [],
    buyWayList: [],
    buyAreaList: [],
    cityList: [
      '河南',
      '广东',
      '江苏',
      '河北',
      '浙江',
      '上海',
      '山东',
      '福建',
      '江西',
      '陕西',
      '湖南',
      '四川',
      '湖北',
      '贵州',
      '安徽',
      '北京',
      '山西',
      '广西',
      '甘肃',
      '辽宁',
      '吉林',
      '重庆',
      '天津',
      '黑龙江',
      '云南',
      '内蒙古',
      '海南',
      '宁夏',
      '西藏',
      '青海',
      '新疆',
      '香港',
      '澳门',
      '台湾'
    ],
    Shop: {
      shareUserId: '',
      title: '',
      contactName: '',
      contactPhone: '',
      buyBudget: '',
      buyArea: '',
      buyWay: '',
      shopFloorNumber: '',
      shopFloorHigh: '',
      buyLocation: '',
      otherRequirement: ''
    },
    showRedPacketDialog: false,
    totalMoney: 0
  },

  onShow() {
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'Shop.shareUserId': shareUserId
      })
    }, 1000)
    if (!check()) return
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    if (+options.id) {
      this.getDetail()
    } else {
      this.getDraft()
      this.setData({
        showRedPacketDialog: true
      })
    }
  },

  getDetail() {
    shopModel.buyShopDetail(
      {
        id: this.data.id
      },
      (res) => {
        wx.hideLoading()
        this.setData({
          Shop: res
        })
        if (res.auditStatus == 2) {
          Dialog.alert({
            title: '审核未通过',
            message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`
          }).then(() => {
            // on close
          })
        }
      }
    )
  },

  publish() {
    let Shop = this.data.Shop
    console.log(Shop, 'sssssh222222op')
    if (!Shop.title) {
      wx.showToast({
        title: '请填写卖店标题',
        icon: 'none'
      })
      return
    }
    if (!Shop.buyArea) {
      wx.showToast({
        title: '请填写求购面积',
        icon: 'none'
      })
      return
    }
    if (!Shop.buyWay) {
      wx.showToast({
        title: '请选择求购方式',
        icon: 'none'
      })
      return
    }
    if (!Shop.buyBudget) {
      wx.showToast({
        title: '请填写求购预算',
        icon: 'none'
      })
      return
    }
    if (!Shop.contactName) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return
    }
    if (!Shop.contactPhone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      })
      return
    }
    if (/^[0-9]*$/.test(Shop.contactName)) {
      wx.showToast({
        title: '联系人不可以是数字',
        icon: 'none'
      })
      return
    }
    if (!Shop.buyLocation) {
      wx.showToast({
        title: '请选择求购区域',
        icon: 'none'
      })
      return
    }
    if (Shop.contactPhone.includes('*')) {
      delete Shop.contactPhone
    }
    this.removeDraft()
    shopModel.publishBuyShop(Shop, (res) => {})
    wx.navigateTo({
      url: `/pages/pay-join/pay-join?type=买店&data=${JSON.stringify(Shop)}`
    })
  },

  update() {
    // updateBuyShop
    let Shop = this.data.Shop
    Dialog.confirm({
      message: '更新后需再次审核\n 是否确认更新？'
    }).then(() => {
      if (Shop.contactPhone.includes('*')) {
        delete Shop.contactPhone
      }
      shopModel.updateBuyShop(Shop, (res) => {
        Dialog.alert({
          title: '更新成功！',
          message: `平台将在24小时内完成审核，请耐心等待！`
        }).then(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.navigateBack()
            }
          })
        })
      })
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  onReady() {
    this.init()
  },

  inputChange(evevt) {
    let key = `Shop.${evevt.currentTarget.dataset.type}`
    if (
      key == 'Shop.buyArea' ||
      key == 'Shop.contactPhone' ||
      key == 'Shop.buyBudget' ||
      key == 'Shop.shopFloorNumber' ||
      key == 'Shop.shopFloorHigh'
    ) {
      evevt.detail = evevt.detail
        .replace(/[^\d^\.]+/g, '')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    }
    this.setData({
      [key]: evevt.detail
    })
  },

  onShowPopup(e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key]: true
    })
  },

  onClosePopup() {
    // 关闭弹窗
    for (let key in this.data.showPopup) {
      key = `showPopup.${key}`
      this.setData({
        [key]: false
      })
    }
  },

  onBuyWay(e) {
    // 选择转让方式
    this.setData({
      'Shop.buyWay': e.detail.selected
    })
  },

  onBuyArea(e) {
    // 选择店铺面积
    this.setData({
      'Shop.buyArea': e.detail.selected
    })
  },

  onBuyLocation(e) {
    // 选择求购区域
    this.setData({
      'Shop.buyLocation': e.detail
    })
  },
  getBuyWay() {
    // 获取转让方式
    publishModel.getPublicTypes(
      {
        tagKey: '购入方式',
        type: 1
      },
      (res) => {
        this.setData({
          buyWayList: res
        })
      }
    )
  },

  delete() {
    Dialog.confirm({
      message: '删除后信息将不再展示，且不可恢复！是否确认删除？'
    }).then(() => {
      shopModel.deleteBuyShop(
        {
          id: this.data.id
        },
        (res) => {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      )
    })
  },

  getArea() {
    // 获取商铺面积
    publishModel.getPublicTypes(
      {
        tagKey: '商铺面积',
        type: 1
      },
      (res) => {
        this.setData({
          buyAreaList: res
        })
      }
    )
  },

  saveDraft() {
    wx.setStorageSync('buyShopData', this.data.Shop)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const Shop = wx.getStorageSync('buyShopData') || this.data.Shop
    this.setData({
      Shop
    })
  },

  removeDraft() {
    wx.removeStorageSync('buyShopData')
  },

  closeRedDialog() {
    this.setData({
      showRedPacketDialog: false
    })
  },

  getPacketSize() {
    packetModel.getPacketSize((res) => {
      res.forEach((item) => {
        if (item.modeName == '买店') {
          this.setData({
            totalMoney: item.totalMoney
          })
        }
      })
    })
  },

  touchmove() {
    // 空函数 防止滚动
  },

  init() {
    this.getBuyWay()
    this.getArea()
    this.getPacketSize()
  }
})
